package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.R;
import com.lzx.iteam.adapter.QrGroupAdapter;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import io.rong.imageloader.core.ImageLoader;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.lzx.iteam.DialerApp.mContext;

/**
 * Created by zhangshuai on 15-5-21.
 */
public class QrCodeAddActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener {


    private QrGroupAdapter mAdapter;
    private ArrayList<String> mDatas;
    private ArrayList<CloudGroup> mGroupListData;
    private ListView mContactList;
    private ImageLoader mImageLoader;
    private CloudGroupListCenter mCenter;
    private TextView mLocalUserMsg;
    private LinearLayout mBack;
    private TextView mSave;
    private ImageView mIvSelect;
    private Dialog mDialog;

    private String mName,mPhone,mPhoneMore,mEmail,mAddress;
    private String mCompany,mJob,mDepartment;
    private String mGroupId,mTagId;
    private String mSid;
    private boolean isLocal = true; // 是不是添加到本地的标识

    public static  final int MESSAGE = 1250;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MESSAGE:
                    if (msg.arg1 == 0){
                        JSONObject result = (JSONObject) msg.obj;
                        try {
                            String contact_id = result.getString("data");
//                            Toast.makeText(QrCodeAddActivity.this,""+contact_id,Toast.LENGTH_SHORT).show();
                            Toast.makeText(QrCodeAddActivity.this,"添加成功",Toast.LENGTH_SHORT).show();
                            finish();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }else{
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(QrCodeAddActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(QrCodeAddActivity.this,(String)msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    mDialog.dismiss();
                    break;
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_list_layout);
        initView();
        initProperty();
        getData();

    }

    public void initView(){
        mContactList = (ListView) findViewById(R.id.qrcode_lv);
        mBack = (LinearLayout) findViewById(R.id.qrcode_ll_back);
        mBack.setOnClickListener(this);
        mSave = (TextView) findViewById(R.id.qrcode_tv_save);
        mSave.setOnClickListener(this);

    }

    public void initProperty(){
        mImageLoader = ImageLoader.getInstance();
        mAdapter = new QrGroupAdapter(this,mImageLoader);
        String uid = PreferenceUtil.getInstance(this).getString(PreferenceUtil.CLIENT_USEID,"");
        CloudDBOperation mCloudDBOperation = new CloudDBOperation(this);
        mGroupListData = mCloudDBOperation.getLocalGroupList(uid);
        //mContactList.addHeaderView(initHeadView());
        mContactList.setAdapter(mAdapter);
        mContactList.setOnItemClickListener(this);
        mAdapter.updateCloudGroupList(mGroupListData);
        mDialog = AllDialogUtil.getInstance(this).waitDialog();

    }

    public View initHeadView() {
        View view = LayoutInflater.from(this).inflate(R.layout.qrcode_group_head_item, null);
        mLocalUserMsg =(TextView)view.findViewById(R.id.group_use_msg);
        if (ContactsDBReader.ALL_CONTACTS_NUMBER == 0 || ContactsDBReader.mGroupList.isEmpty() || ContactsDBReader.mNoGroupsSet.isEmpty()) {
            ContactsDBReader.resetAllContactsNumber(this);
            mLocalUserMsg.setText(ContactsDBReader.ALL_CONTACTS_NUMBER +"个联系人");
        }else{
            mLocalUserMsg.setText(ContactsDBReader.ALL_CONTACTS_NUMBER +"个联系人");
        }
        mIvSelect = (ImageView) view.findViewById(R.id.qrcode_head_select);
        return view;
    }

    public void getData(){
        mDatas = getIntent().getStringArrayListExtra(ResultActivity.QRCODE_DATA);
        mName = mDatas.get(0) == null ? "" : mDatas.get(0);
        mPhone = mDatas.get(1) == null ? "" : mDatas.get(1);
        //mPhoneMore = mDatas.get(2) == null ? "" : mDatas.get(2);
        mCompany = mDatas.get(3) == null ? "" : mDatas.get(3);
        mJob = mDatas.get(4) == null ? "" : mDatas.get(4);
        mEmail = mDatas.get(5) == null ? "" : mDatas.get(5);
        mAddress = mDatas.get(6) == null ? "" : mDatas.get(6);

        mDepartment = "";
        mTagId = "0";
        mSid = LocalLogin.getInstance().mSid;
        Log.i("QRCODE_DATA",mDatas.toString());
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.qrcode_ll_back:
                finish();
                break;
            case R.id.qrcode_tv_save:
                if (!StringUtil.isEmpty(mGroupId)){
                    mDialog.show();
                    insertContact();
                }else{
                    Toast.makeText(this,"请选择团队",Toast.LENGTH_SHORT).show();
                }

                /*if (isLocal){
                    toSaveContactInfo();
                }else{
                    insertContact();
                }*/
                break;
        }

    }

    /**
     * 保存到云号码簿
     */
    public void insertContact(){

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("group_id",mGroupId));
        nvps.add(new BasicNameValuePair("tag_id",mTagId));
        nvps.add(new BasicNameValuePair("user_phone",mPhone));
        nvps.add(new BasicNameValuePair("sid",mSid));

        InsertMessage message = new InsertMessage(mHandler.obtainMessage(MESSAGE));
        message.mApi = AsynHttpClient.API_CONTACT_SCANING;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(message);
    }

    class InsertMessage extends CcMsgStructure{

        private Message mmCallback;

        public InsertMessage(Message callback){
            this.mmCallback = callback;
        }

        @Override
        public void onReceive(JSONObject data) {
            if (mmCallback != null){
                mmCallback.obj = data;
                mmCallback.sendToTarget();
            }
        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if(mmCallback != null){
                mmCallback.arg1 = error;
                if(!StringUtil.isEmpty(errorMsg)){
                    mmCallback.obj = errorMsg;
                }else{
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    /**
     * 保存到本地
     * 暂时去掉了，呵呵哒
     */
    private void toSaveContactInfo() {

        ContentValues values = new ContentValues();
        // 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获取系统返回的rawContactId
        Uri rawContactUri = this.getContentResolver().insert(
                ContactsContract.RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);

        // 往data表入姓名数据
        values.clear();
        values.put(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,mName);
        this.getContentResolver().insert(
                android.provider.ContactsContract.Data.CONTENT_URI, values);

        // 添加用户名 职位 部门
        values.clear();
        values.put(
                android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                rawContactId);
        values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
//        values.put(Organization.LABEL, mEmployee.getUserName());
        values.put(ContactsContract.CommonDataKinds.Organization.TITLE, mJob);
        values.put(ContactsContract.CommonDataKinds.Organization.COMPANY, mCompany);
        values.put(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK);
        this.getContentResolver().insert(
                android.provider.ContactsContract.Data.CONTENT_URI, values);

        // 添加邮箱
        if (!StringUtil.isEmpty(mEmail)){

            values.clear();
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Email.DATA, mEmail);
            values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.AWAY);
            this.getContentResolver().insert(
                    android.provider.ContactsContract.Data.CONTENT_URI, values);
        }
        // 添加手机
        /*if (mEmployee.getMobile().contains("或")) {
            final String[] tNumbers = mEmployee.getMobile().split("或");
            for (String tNum : tNumbers) {
                values.clear();
                values.put(
                        android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                        rawContactId);
                values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
                values.put(Phone.NUMBER, tNum);
                values.put(Phone.TYPE, Phone.TYPE_WORK_MOBILE);
                context.getContentResolver().insert(
                        android.provider.ContactsContract.Data.CONTENT_URI,
                        values);
            }
        } else {*/
        values.clear();
        values.put(
                android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                rawContactId);
        values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, mPhone);
        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE);
        this.getContentResolver().insert(
                android.provider.ContactsContract.Data.CONTENT_URI, values);

        /*if ( !StringUtil.isEmpty(mPhoneMore)){
            values.clear();
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, mPhoneMore);
            values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE);
            this.getContentResolver().insert(
                    android.provider.ContactsContract.Data.CONTENT_URI, values);
        }*/
//        }

//        }


        /*// 添加固定电话
        values.clear();
        values.put(
                android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                rawContactId);
        values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        values.put(Phone.NUMBER, mEmployee.getOfficeTel());
        values.put(Phone.TYPE, Phone.TYPE_WORK);
        context.getContentResolver().insert(
                android.provider.ContactsContract.Data.CONTENT_URI, values);
        // 添加传真
        values.clear();
        values.put(
                android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                rawContactId);
        values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        values.put(Phone.NUMBER, mEmployee.getFax());
        values.put(Phone.TYPE, Phone.TYPE_FAX_WORK);
        context.getContentResolver().insert(
                android.provider.ContactsContract.Data.CONTENT_URI, values);*/
        // 添加地址
        if (!StringUtil.isEmpty(mAddress)){
            values.clear();
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, mAddress);
            // 邮编
//            values.put(StructuredPostal.POSTCODE, mEmployee.getPostCode());
            values.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME);
            this.getContentResolver().insert(
                    android.provider.ContactsContract.Data.CONTENT_URI, values);
        }
        values.clear();
        /*// 添加头像
        values.clear();
        values.put(
                android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                rawContactId);
        values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
        values.put(Photo.PHOTO, bytes);
        context.getContentResolver().insert(
                android.provider.ContactsContract.Data.CONTENT_URI, values);*/
        mDialog.dismiss();
        Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        int groupType = mGroupListData.get(i).groupType ;
        String userType = mGroupListData.get(i).userType;

        if (userType.equals("2") || userType.equals("3") ){
            mAdapter.setSelect(i);
            mGroupId = mGroupListData.get(i).groupId + "";
        }else{
            if (groupType == 1){
                mAdapter.setSelect(i);
                mGroupId = mGroupListData.get(i).groupId + "";
            } else{
                Toast.makeText(QrCodeAddActivity.this,"不允许添加新人",Toast.LENGTH_SHORT).show();
            }
        }

           /* if ( i == 0){
                mIvSelect.setVisibility(View.VISIBLE);
                mAdapter.setSelect(-1);
                isLocal = true;
            }else{
                String userType = mGroupListData.get(i -1).userType;
                if (userType.equals("2") || userType.equals("3") ){
                    mAdapter.setSelect(i-1);
                    mIvSelect.setVisibility(View.GONE);
                    mGroupId = mGroupListData.get(i - 1).groupId + "";
                    isLocal = false;
                }else{
                    Toast.makeText(QrCodeAddActivity.this,"你没有权限",Toast.LENGTH_SHORT).show();
                }

            }*/

    }
}
